package com.lrkj.back.vo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lrkj.back.entity.Cycledata;
import com.lrkj.back.vo.json.XML;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultText;

import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by daiwe on 2017/6/22.
 */
public class MyXMLReader {

    // public static void test(String args []){
    // long lasting = System.currentTimeMillis();
    // try{
    // File f = new File("D:text.xml");
    // DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // DocumentBuilder builder = factory.newDocumentBuilder();
    // Document doc = builder.parse(f);
    // NodeList n1 = doc.getElementsByTagName("VALUE");
    // for(int i = 0;i<n1.getLength();i++){
    // System.out.print(""+doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue());
    // System.out.println("车主地址:" +
    // doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue());
    // }
    //
    // }catch (Exception e ){
    // e.printStackTrace();
    // }
    // }

    public static List<Cycledata> getData(Element node) throws IOException, ParseException {

        // 读取src下的xml文件
        File file = new File("D:/file/10.xml");

        // 字符流输出
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
        String string = null;
        StringBuffer sb = new StringBuffer();
        while ((string = reader.readLine()) != null) {
            sb.append(string);
        }

        // 将xml转为json
        com.lrkj.back.vo.json.JSONObject xmlJSONObj = XML.toJSONObject(sb.toString());
        String json = xmlJSONObj.toString();
        JSONObject todcJson = (JSONObject) JSONObject.parse(json);
        JSONArray jsonArray = todcJson.getJSONObject("TDOCLOGPACKET").getJSONObject("CYCLE").getJSONObject("CYCLEDATA")
                .getJSONObject("LOGDATA").getJSONArray("ROW");
        List<Cycledata> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            System.out.print("1");
            Cycledata cycledata = new Cycledata();
            JSONObject o = (JSONObject) jsonArray.get(i);
            String ct = o.getString("CT");
            String time = o.getString("TIME");
            String cp = o.getString("CP");
            String phase = o.getString("PHASE");
            cycledata.setPhase(phase);
            if (cp != null)
                cycledata.setCp(BigDecimal.valueOf(Double.valueOf(cp)));
            if (ct != null)
                cycledata.setCp(BigDecimal.valueOf(Double.valueOf(ct)));
            if (time != null) {

                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                Date date = sdf.parse(time);
                cycledata.setTime(date);
            }

            list.add(cycledata);

        }
        // List<Cycledata> cycledataList =
        // jsonArray.toJavaList(Cycledata.class);

        System.out.println(todcJson.toString());
        System.out.println(list);

        // 设置缩进
        // String jsonPrettyPrintString = xmlJSONObj.toString(2);
        // 输出格式化后的json
        System.out.println(xmlJSONObj.toString(4));
        return list;

    }

    public static Map<String, String> parseXml() {

        Map<String, String> map = new HashMap<String, String>();
        InputStream inputStream = null;
        try {
            // inputStream = request.getInputStream();
            FileInputStream fileInputStream = new FileInputStream("D:/file/10.xml");

            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(fileInputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            Element foo;

            List<Element> logdata = root.elements();
            List<Element> logList = root.elements();
            for (int i = 0; i < logList.size(); i++) {
                Element element = logList.get(i);
                element.getQName();
                List<DefaultText> elList = element.content();
                for (int j = 0; j < elList.size(); j++) {
                    DefaultText content = elList.get(i);
                    Document element1 = content.getDocument();
                    element1.addComment("dd");
                }
                String da = element.elementText("TIME");
            }
            // List<Cycledata> cycledataList = listNodes(root);
            getData(root);
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();
            // System.out.print(cycledataList);

        } catch (Exception e) {
            e.printStackTrace();
            return map;
        } finally {
            try {
                if (inputStream != null) {
                    // 释放资源
                    inputStream.close();
                    inputStream = null;
                }
            } catch (Exception e) {
            }
        }
        return map;
    }

    public static void main(String args[]) {
        Map<String, String> map = parseXml();
    }

    public static List<Cycledata> listNodes(Element node) {

        List<Cycledata> cycledataList = new ArrayList<>();
        Cycledata cycledata = new Cycledata();
        System.out.println("当前节点的名称：" + node.getName());
        if (node.getName() == "TIME") {
            node.getText();
        }
        if (node.getName() == "CP") {
            BigDecimal bigDecimal = BigDecimal.valueOf(Double.valueOf(node.getText()));
            cycledata.setCp(bigDecimal);
        }
        if (node.getName() == "CT") {
            cycledata.setCp(BigDecimal.valueOf(Double.valueOf(node.getText())));
        }
        if (node.getName() == "PHASE") {
            cycledata.setPhase(node.getText());

        }
        cycledataList.add(cycledata);
        // 首先获取当前节点的所有属性节点
        List<Attribute> list = node.attributes();

        // 遍历属性节点
        for (Attribute attribute : list) {

            System.out.println("属性" + attribute.getName() + ":" + attribute.getValue());
        }
        // 如果当前节点内容不为空，则输出
        if (!(node.getTextTrim().equals(""))) {
            System.out.println(node.getName() + "：" + node.getText());
        }
        // 同时迭代当前节点下面的所有子节点
        // 使用递归
        Iterator<Element> iterator = node.elementIterator();
        while (iterator.hasNext()) {
            Element e = iterator.next();
            listNodes(e);
        }
        return cycledataList;
    }
}
